import type { LoginAndRegisterParams,ResetPasswordParams } from '@vben/common-ui';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';

import { getUserInfoApi, loginApi, registerApi, resetPasswordApi } from '#/api';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: LoginAndRegisterParams,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: any = null;
    try {
      loginLoading.value = true;
      const { access_token, refresh_token, user } = await loginApi(params);

      // 如果成功获取到 accessToken
      if (access_token) {
        // 将 accessToken 存储到 accessStore 中
        accessStore.setAccessToken(access_token);
        accessStore.setRefreshToken(refresh_token);

        // 获取用户信息并存储到 accessStore 中
        // const [fetchUserInfoResult, accessCodes] = await Promise.all([
        //   fetchUserInfo(),
        //   getAccessCodesApi(),
        // ]);

        userInfo = user;

        userStore.setUserInfo(userInfo);
        // accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          
        }

        localStorage.setItem('accessToken', access_token);

        onSuccess
        ? await onSuccess?.()
        : await router.push(userInfo.homePath || DEFAULT_HOME_PATH);

        if (userInfo?.name) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.name}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout() {
    resetAllStores();
    accessStore.setLoginExpired(false);
    localStorage.setItem('accessToken', '');
    // 回登陆页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: {
        redirect: encodeURIComponent(router.currentRoute.value.fullPath),
      },
    });
  }

  async function fetchUserInfo() {
    let userInfo: any = null;
    userInfo = await getUserInfoApi();
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  /**
   * 异步处理注册操作
   * Asynchronously handle the register process
   * @param params 注册表单数据
   */
  async function authRegister(
    params: LoginAndRegisterParams,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户注册操作
    let userInfo: any = null;
    try {
      loginLoading.value = true;
      const { code, err, desc } = await registerApi(params);

      // 如果成功注册
      if (code === "200") {
          notification.success({
            description: desc,
            duration: 3,
            message: desc,
          });

          //注册成功跳转到登录页
          onSuccess
            ? await onSuccess?.()
            : await router.push(LOGIN_PATH);
      }else{
        notification.error({
          description: err,
          duration: 3,
          message: desc,
        });
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }  

    /**
   * 异步处理注册操作
   * Asynchronously handle the register process
   * @param params 注册表单数据
   */
    async function authResetPassword(
      params: ResetPasswordParams,
      onSuccess?: () => Promise<void> | void,
    ) {
      // 异步处理用户注册操作
      let userInfo: any = null;
      try {
        loginLoading.value = true;
        const { code, err, desc } = await resetPasswordApi(params);
  
        // 如果成功重置密码
        if (code === "200") {
            notification.success({
              description: desc,
              duration: 3,
              message: desc,
            });
  
            //重置密码成功跳转到登录页
            onSuccess
              ? await onSuccess?.()
              : await router.push(LOGIN_PATH);
        }else{
          notification.error({
            description: err,
            duration: 3,
            message: desc,
          });
        }
      } finally {
        loginLoading.value = false;
      }
  
      return {
        userInfo,
      };
    }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
    authRegister,
    authResetPassword
  };
});
